package company_secret

import (
	"context"
	"crypto/rand"
	"encoding/base64"
	"upgradelink-admin-core/server/rpc/types/core"

	"upgradelink-admin-core/server/api/internal/svc"
	"upgradelink-admin-core/server/api/internal/types"

	"github.com/suyuan32/simple-admin-common/orm/ent/entctx/userctx"
	"github.com/zeromicro/go-zero/core/logx"
)

type CreateCompanySecretLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCreateCompanySecretLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateCompanySecretLogic {
	return &CreateCompanySecretLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreateCompanySecretLogic) CreateCompanySecret(req *types.CompanySecretInfo) (resp *types.BaseMsgResp, err error) {
	// 获取公司 id
	userId, err := userctx.GetUserIDFromCtx(l.ctx)
	if err != nil {
		return nil, err
	}
	userData, err := l.svcCtx.CoreRpc.GetUserById(l.ctx, &core.UUIDReq{
		Id: userId,
	})
	if err != nil {
		return nil, err
	}

	// 生产密钥
	accessKey, secretKey, _ := generateAPIKeys()

	data, err := l.svcCtx.CoreRpc.CreateCompanySecret(l.ctx,
		&core.CompanySecretInfo{
			CompanyId:   userData.CompanyId,
			AccessKey:   &accessKey,
			SecretKey:   &secretKey,
			Enable:      req.Enable,
			IsDel:       req.IsDel,
			Description: &req.Description,
		})
	if err != nil {
		return nil, err
	}

	return &types.BaseMsgResp{Msg: l.svcCtx.Trans.Trans(l.ctx, data.Msg)}, nil
}

// generateAPIKeys 生成安全随机的AccessKey和SecretKey
func generateAPIKeys() (accessKey string, secretKey string, err error) {
	// 生成Access Key (16字节 -> 24字符Base64)
	accessBytes := make([]byte, 16)
	if _, err := rand.Read(accessBytes); err != nil {
		return "", "", err
	}
	accessKey = base64.RawURLEncoding.EncodeToString(accessBytes)

	// 生成Secret Key (32字节 -> 43字符Base64)
	secretBytes := make([]byte, 32)
	if _, err := rand.Read(secretBytes); err != nil {
		return "", "", err
	}
	secretKey = base64.RawURLEncoding.EncodeToString(secretBytes)

	return accessKey, secretKey, nil
}
